package com.study.kafkademo.kafka.custom;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.study.kafkademo.kafka.custom.model.KafkaMessage;
import com.study.kafkademo.kafka.custom.model.KafkaMessageHeader;
import com.study.kafkademo.kafka.custom.model.MsgTemplate;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.kafka.support.KafkaHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;

@Component
@Slf4j
public class CustomKafkaConsumer {

    @KafkaListener(topics = CustomKafkaProducer.TOPIC_TEST, groupId = CustomKafkaProducer.TOPIC_GROUP1, containerFactory = "kafkaListenerContainerFactory")
    public void topic_test(List<ConsumerRecord<?, ?>> records, Acknowledgment ack) {
        try {
            log.info("此线程消费" + records.size() + "条消息----线程名:" + Thread.currentThread().getName());
            records.forEach(record -> {
                log.info("topic={}, partition={}, key={}, offset={}, value={}",
                        record.topic(), record.partition(), record.key(), record.offset(), record.value());

                final String s = record.value().toString();
                JSONObject.parseObject(s, KafkaMessage.class);
                KafkaMessage<MsgTemplate> kafkaMessage = JSON.parseObject(s, new TypeReference<KafkaMessage<MsgTemplate>>() {
                });
                KafkaMessageHeader header = kafkaMessage.getMessageHeader();
                MsgTemplate template = kafkaMessage.getDate();
            });
        } catch (Exception e) {
            log.error("kafka消息消息异常:{}", e);
        } finally {
            //手动提交偏移量
            ack.acknowledge();
        }
    }

    @KafkaListener(topics = CustomKafkaProducer.TOPIC_TEST, groupId = CustomKafkaProducer.TOPIC_GROUP2)
    public void topic_test1(ConsumerRecord record, Acknowledgment ack, @Header(KafkaHeaders.RECEIVED_TOPIC) String
            topic) {
        final Optional<ConsumerRecord> message = Optional.ofNullable(record);
        if (message.isPresent()) {
            final ConsumerRecord consumerRecord = message.get();
            log.info("topic_test1 消费了： topic：" + topic + ";;; message :" + consumerRecord);
            ack.acknowledge();
        }
    }
}
